<template lang="pug">
.page
  .CustomerSalary
    .search-form.mb-10.pr-10
      Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
        FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'select'")
            Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
              Option(
                v-for="(c_item, index) in arrListDown[item.options]"
                :value="c_item.value"
                :key="index"
              ) {{ c_item.label }}
          template(v-if="item.type === 'input'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(:value="formData[item.model]" :placeholder="item.placeholder" type="year" @on-change="handleChangeDatePicker(item.model, $event)")
          template(v-if="item.type === 'cascader'")
            .areaTree
              Cascader(v-model="formData[item.model]" :data="areaTree" clearable change-on-select @on-change="areaTreeChange(item.model, $event)")
          template(v-if="item.type === 'button'")
            Button(v-if="hasFind" type="info" @click="searchFn") 查询

    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true"
        @on-selection-change="handleOnSelectChange"
      )
        .clearfix.font-16(slot="header")
          .table-title-lefttxt.pull-left
            |合计
            span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
            |条
          .pull-right.table-title-btns
            Button.mr-10(v-if="hasImport" type="info" @click="handleShowBatchImportSalaryModal") 批量导入
            Button.mr-10(v-if="hasDelete" type="warning" @click="handleDelete" :disabled="!selectedIdArr.length > 0") 删除

        template(slot-scope="{ row, index }" slot="action")
          Button( v-if="hasViewDetail" type="text" size="small" @click="goCustomerSalaryDetail(row.id, row.year)") 明细

        .clearfix.pl-20.pr-20(slot="footer")
          Page(
            :current="tableComone.pageIndex"
            :total="tableComone.totalRows"
            @on-change="onChangePage"
            @on-page-size-change="onpageSizeChange"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )

    //- CustomerSalaryImportModal(ref="CustomerSalaryImportModal" @uploadFileOk="uploadFileOk" @uploadSuccess="handleUploadSuccess")
    //- //- 薪资导入弹窗
    //- CustomerSalaryImportModal(ref="CustomerSalaryImportModal" @query="searchFn")
    //- //- 批量导入弹窗
    BatchImportSalaryModal(ref="BatchImportSalaryModal" :axsEnableSwitch="axsEnableSwitch" @handleMaxSizeTen="handleMaxSizeTen" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { SysInitCustomerSalaryApi } from '@/api/SysInitCustomerSalary.api.js'
import { salaryThead } from './CStableHead.js'
import _cloneDeep from 'clone-deep'
// import CustomerSalaryImportModal from './modal/CustomerSalaryImportModal.vue'
import BatchImportSalaryModal from './modal/batchImportSalaryModal.vue'
import { ProvinceList, AreaTree } from '@/utils/publicJson.js'
export default {
  name: 'SysInitCustomerSalary',

  components: {
    // CustomerSalaryImportModal,
    BatchImportSalaryModal
  },

  data () {
    return {
      thead: _cloneDeep(salaryThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      formData: {
        name: '',
        month: new Date(),
        cooperateType: '',
        cityId: [],
        serverId: ''
      },
      formItem: [
        { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'name', model: 'name', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'select', label: '合作类型：', placeholder: '请选择合作类型', prop: 'cooperateType', model: 'cooperateType', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8', options: 'type' },
        { type: 'select', label: '所属客服：', placeholder: '请选择所属客服', prop: 'serverId', model: 'serverId', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8', options: 'server' },
        { type: 'datePicker', label: '年度：', placeholder: '请选择年度', prop: 'year', model: 'year', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-4' }
      ],
      rules: {},
      arrListDown: {
        type: [],
        server: []
      },
      areaArr: [], // 区域数组
      selectedId: '', // 勾选的id集合
      selectedIdArr: [], // 勾选的id, name数组集合
      axsEnableSwitch: false,
      areaTree: [] // 中国所有城市树
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导入
    hasDelete () {
      return this.actionArr.indexOf('Delete') > -1
    },
    // 薪资明细
    hasViewDetail () {
      return this.actionArr.indexOf('ViewDetail') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 批量导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },

  },

  watch: {
  },

  mounted () {
    this.servers()
    this.getEnum()
    this.query()
    this.getJson()
  },

  methods: {
    async getJson () {
      console.log('🍌')
      // this.arrListDown.cityId = ProvinceList // 全国省份列表
      this.areaTree = AreaTree // 获取中国所有城市树
      console.log('🌰')
      console.log('this.formData 🌰', this.formData)
    },

    // 数据字典
    getEnum () {
      let groupName = 'customer.type'
      Common.getEnum(groupName, this.arrListDown)
      // console.log('数据字典：', this.arrListDown.status)
    },

    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      console.log('query')
      var params = {
        CooperateType: this.formData.cooperateType,
        CityId: this.formData.cityId[this.formData.cityId.length - 1],
        ServerId: this.formData.serverId,
        HasPaging: true,
        CustomerName: this.formData.name,
        Year: this.formData.year,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await SysInitCustomerSalaryApi.getList(params)
      console.log('客户薪资res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.axsEnableSwitch = res.data.axsEnableSwitch

        this.selectedIdArr = []
        this.selectedId = ''
      } else {
        this.tableData = []
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.loading = false
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    goCustomerSalaryDetail (id, year) {
      this.$router.push({
        path: '/SysInitCustomerSalaryDetail',
        name: 'SysInitCustomerSalaryDetail',
        query: {
          id: id,
          year: year
        }
      })
    },

    // 导入薪资弹窗
    handleShowCustomerSalaryImportModal () {
      this.$refs.CustomerSalaryImportModal.show() // 显示弹窗
      this.$refs.CustomerSalaryImportModal.errorData.isError = false // 隐藏错误数据下载按钮
      this.$refs.CustomerSalaryImportModal.isCanUpload = true // 可导入按钮
      this.$refs.CustomerSalaryImportModal.salaryStartTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), // 上个月1号
      this.$refs.CustomerSalaryImportModal.salaryEndTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 30), // 上个月30号
      this.$refs.CustomerSalaryImportModal.handleClearFiles()
    },

    // 批量导入-显示弹窗
    handleShowBatchImportSalaryModal () {
      this.$refs.BatchImportSalaryModal.show()
      this.$refs.BatchImportSalaryModal.file = null
      this.$refs.BatchImportSalaryModal.errorData.isError = false
      // this.$refs.BatchImportSalaryModal.year = this.$moment(this.tableData[0].salaryMonth).format('YYYY')
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedIdArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      let arr = value.map((item) => {
        return item.id
      })
      this.selectedId = arr.join(',')
      console.log('列表勾选数组', this.selectedIdArr)
      console.log('列表勾选数组字符串', this.selectedId)
    },

    // 日期选择
    datePickerChange (e) {
      this.formData.month = e
    },

    async handleDelete () {
      var params = {
        id: this.selectedId
      }
      console.log('🌈', params)
      let res = await SysInitCustomerSalaryApi.delete(params)
      console.log('删除res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.tableComone.pageIndex = 1
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 是否提交财务前询问
    isSubmitFinanceModal (id, month) {
      this.$Modal.confirm({
        title: '是否确认提交财务',
        onOk: () => {
          // console.log('是！')
          this.handleSureSubmitFinance(id, month)
        }
      })
    },

    // 确认提交
    async handleSureSubmitFinance (id, month) {
      var params = {
        ID: id,
        Year: this.$moment(month).format('YYYY') //审核结果
      }
      console.log('params: ', params)
      let res = await CustomerSalaryApi.submitFinance(params)
      if (res.data.success) {
        this.$Message.success(res.data.message)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.query()
    },

    // 时间控件
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
    },

    // 所在地区选择
    areaTreeChange (model, value) {
      this.formData[model] = value
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  }
}
</script>

<style lang="less" scope>
</style>
